import 'dart:ui';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/order_detail_entity.dart';
import 'package:factoryside/bean/order_record_entity.dart';
import 'package:factoryside/generated/json/order_detail_entity_helper.dart';
import 'package:factoryside/generated/json/order_record_entity_helper.dart';
import 'package:factoryside/home/page_change_prod.dart';
import 'package:factoryside/home/page_change_service_type.dart';
import 'package:factoryside/home/page_create_order.dart';
import 'package:factoryside/home/page_leave_msg.dart';
import 'package:factoryside/home/page_order_record.dart';
import 'package:factoryside/home/page_urge.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///工单详情

class OrderDetailPage extends StatefulWidget {
  int orderId;

  OrderDetailPage(this.orderId);

  @override
  State<StatefulWidget> createState() {
    return _OrderDetailState();
  }
}

class _OrderDetailState extends State<OrderDetailPage>
    with AutomaticKeepAliveClientMixin {
  OrderDetailEntity order;
  List<OrderRecordEntity> tempList = [];
  @override
  void initState() {
    super.initState();
    print('orderId:${widget.orderId}');
    getOrderDetail();
  }

  void getOrderDetail() {
    RequestUtil.get('${Api.getOrderDetail}?orderId=${widget.orderId}', {})
        .then((value) {
      order =
          orderDetailEntityFromJson(OrderDetailEntity(), value['Data']['data']);
      RequestUtil.post('${Api.getOrderRecordByGrid}',
          {'orderId': widget.orderId, 'limit': '5'}).then((value) {
        setState(() {
          List list = value['Data']['data'];
          tempList = [];
          if (list.length > 5) {
            List.generate(
                5,
                (index) => tempList.add(orderRecordEntityFromJson(
                    OrderRecordEntity(), list[index])));
          } else {
            list.forEach((element) {
              tempList
                  .add(orderRecordEntityFromJson(OrderRecordEntity(), element));
            });
          }
        });
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    getOrderDetail();
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    // TODO: implement build
    return Scaffold(
      appBar: buildAppBar('工单详情', [], context),
      body: order == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : Container(
              color: Color(0xffEFEFEF),
//            color: Color(0xffffffff),
              child: Column(
                children: [
                  Expanded(
                    child: SmartRefresher(
                        enablePullDown: true,
                        enablePullUp: false,
                        controller: _refreshController,
                        onRefresh: _onRefresh,
                        child: CustomScrollView(
                          physics: BouncingScrollPhysics(),
                          slivers: <Widget>[
                            SliverList(
                              delegate: SliverChildListDelegate([
                                Container(
                                    color: Colors.white,
                                    padding: EdgeInsets.all(10),
                                    margin: EdgeInsets.symmetric(vertical: 10),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Expanded(
                                                child: Text('基本信息',
                                                    style: TextStyle(
                                                        fontWeight:
                                                            FontWeight.bold))),
                                            OutlinedButton(
                                                onPressed: () {
                                                  showToast('复制');
                                                },
                                                child: Text('复制',
                                                    style: TextStyle(
                                                        color: Colors.red)),
                                                style: ButtonStyle(
                                                    side: MaterialStateProperty
                                                        .all(BorderSide(
                                                            color:
                                                                Colors.red))))
                                          ],
                                        ),
                                        Wrap(
                                          spacing: 5,
                                          runSpacing: 5,
                                          children: List.generate(
                                              2,
                                              (element) => Container(
                                                    padding:
                                                        EdgeInsets.symmetric(
                                                            vertical: 3,
                                                            horizontal: 5),
                                                    decoration: BoxDecoration(
                                                        color: colors[element],
                                                        borderRadius:
                                                            BorderRadius.all(
                                                                Radius.circular(
                                                                    2))),
                                                    child: Text(
                                                      element == 0
                                                          ? '${order.stateHtml}'
                                                          : '${order.guarantee == 'Y' ? '保内' : '保外'}${order.typeName}',
                                                      style: TextStyle(
                                                          fontSize: 10,
                                                          color: Colors.white),
                                                      textAlign:
                                                          TextAlign.center,
                                                    ),
                                                  )).toList(),
                                        ),
                                        Divider(),
                                        Row(
                                          children: [
                                            Text('工单编号：'),
                                            Expanded(
                                                child: Text(
                                              '${order.orderNumber}',
                                              style:
                                                  TextStyle(color: Colors.grey),
                                            )),
                                          ],
                                        ),
//                          Row(
//                            children: [
//                              Text('接单客服：'),
//                              Expanded(child: Text('客服001')),
//                            ],
//                          ),
                                        Row(
                                          children: [
                                            Text('下单时间：'),
                                            Expanded(
                                                child: Text(
                                              '${order.createDate}',
                                              style:
                                                  TextStyle(color: Colors.grey),
                                            )),
                                          ],
                                        ),
//                          Row(
//                            children: [
//                              Row(
//                                children: [
//                                  Image.asset(
//                                    'assets/location.png',
//                                    width: 15,
//                                    height: 15,
//                                  ),
//                                  SizedBox(
//                                    width: 5,
//                                  ),
//                                  Text(
//                                    '1.6km',
//                                    style: TextStyle(fontSize: 12),
//                                  ),
//                                ],
//                              ),
//                              SizedBox(width: 20,),
//                              Row(
//                                children: [
//                                  Image.asset(
//                                    'assets/time.png',
//                                    width: 15,
//                                    height: 15,
//                                  ),
//                                  SizedBox(
//                                    width: 5,
//                                  ),
//                                  Text(
//                                    '56分钟前',
//                                    style: TextStyle(fontSize: 12),
//                                  ),
//                                ],
//                              ),
//                            ],
//                          ),
                                      ],
                                    )),
                                Container(
                                    color: Colors.white,
                                    padding: EdgeInsets.all(10),
                                    margin: EdgeInsets.only(bottom: 10),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Expanded(
                                                child: Text('产品信息',
                                                    style: TextStyle(
                                                        fontWeight:
                                                            FontWeight.bold))),
//                              OutlinedButton(onPressed: (){
//                                showToast('复制');
//                              }, child: Text('复制',style: TextStyle(color: Colors.red)),style: ButtonStyle(side: MaterialStateProperty.all(BorderSide(color: Colors.red))))
                                          ],
                                        ),
                                        Divider(),
                                        Column(
                                          children: List.generate(
                                              order.orderProductModels.length,
                                              (position) => Container(
                                                    padding:
                                                        EdgeInsets.symmetric(
                                                            vertical: 5,
                                                            horizontal: 10),
                                                    margin:
                                                        EdgeInsets.symmetric(
                                                            vertical: 5),
                                                    decoration: BoxDecoration(
                                                        color:
                                                            Color(0xffEBEBEB),
                                                        borderRadius:
                                                            BorderRadius.all(
                                                                Radius.circular(
                                                                    5))),
                                                    child: Column(
                                                      children: [
                                                        Row(
                                                          children: [
                                                            Text('产品品牌：'),
                                                            Expanded(
                                                                child: Text(
                                                              '${order.orderProductModels[position].brandName}',
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .grey),
                                                            )),
                                                          ],
                                                        ),
                                                        Row(
                                                          children: [
                                                            Text('产品类型：'),
                                                            Expanded(
                                                                child: Text(
                                                              '${order.orderProductModels[position].subCategoryName}',
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .grey),
                                                            )),
                                                          ],
                                                        ),
                                                        Row(
                                                          children: [
                                                            Text('产品规格：'),
                                                            Expanded(
                                                                child: Text(
                                                              '${order.orderProductModels[position].productType}',
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .grey),
                                                            )),
                                                          ],
                                                        ),
                                                        Row(
                                                          children: [
                                                            Text('产品型号：'),
                                                            Expanded(
                                                                child: Text(
                                                              '${order.orderProductModels[position].prodModelName}',
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .grey),
                                                            )),
                                                          ],
                                                        ),
                                                        Row(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: [
                                                            Text('服务要求：'),
                                                            Expanded(
                                                                child: Text(
                                                              '${order.orderProductModels[position].memo}',
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .grey),
                                                            )),
                                                          ],
                                                        ),
                                                      ],
                                                    ),
                                                  )).toList(),
                                        ),
                                      ],
                                    )),
                                Container(
                                    color: Colors.white,
                                    padding: EdgeInsets.all(10),
                                    margin: EdgeInsets.only(bottom: 10),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Expanded(
                                                child: Padding(
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      vertical: 5.0),
                                              child: Text('用户信息',
                                                  style: TextStyle(
                                                      fontWeight:
                                                          FontWeight.bold)),
                                            )),
                                          ],
                                        ),
                                        Divider(),
                                        Row(
                                          children: [
                                            Text('姓名：'),
                                            Expanded(
                                                child: Text(
                                              '${order.userName}',
                                              style:
                                                  TextStyle(color: Colors.grey),
                                            )),
                                          ],
                                        ),
                                        Row(
                                          children: [
                                            Text('电话：'),
                                            Expanded(
                                                child: Text(
                                              '${order.phone}',
                                              style:
                                                  TextStyle(color: Colors.grey),
                                            )),
                                          ],
                                        ),
                                        Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text('地址：'),
                                            Expanded(
                                                child: Text(
                                              '${order.address}',
                                              style:
                                                  TextStyle(color: Colors.grey),
                                            )),
                                          ],
                                        ),
                                      ],
                                    )),
                                Visibility(
                                  visible: order.masterInfo != null,
                                  child: Container(
                                      color: Colors.white,
                                      padding: EdgeInsets.all(10),
                                      margin: EdgeInsets.only(bottom: 10),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            children: [
                                              Expanded(
                                                  child: Padding(
                                                padding:
                                                    const EdgeInsets.symmetric(
                                                        vertical: 5.0),
                                                child: Text('师傅信息',
                                                    style: TextStyle(
                                                        fontWeight:
                                                            FontWeight.bold)),
                                              )),
                                            ],
                                          ),
                                          Divider(),
                                          Row(
                                            children: [
                                              Text('姓名：'),
                                              Expanded(
                                                  child: Text(
                                                '${order.masterInfo != null ? order.masterInfo.trueName : '暂无'}',
                                                style: TextStyle(
                                                    color: Colors.grey),
                                              )),
                                            ],
                                          ),
                                          Row(
                                            children: [
                                              Text('电话：'),
                                              Expanded(
                                                  child: Text(
                                                '${order.masterInfo != null ? order.masterInfo.userID : '暂无'}',
                                                style: TextStyle(
                                                    color: Colors.grey),
                                              )),
                                            ],
                                          ),
//                            Row(
//                              crossAxisAlignment: CrossAxisAlignment.start,
//                              children: [
//                                Text('地址：'),
//                                Expanded(child: Text('广西壮族自治区百色市西林县八达镇',style: TextStyle(color: Colors.grey),)),
//                              ],
//                            ),
                                        ],
                                      )),
                                ),
                                Container(
                                    padding: EdgeInsets.all(10),
                                    margin: EdgeInsets.only(bottom: 60),
                                    color: Colors.white,
                                    child: Column(
                                      children: [
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text('工单进度',
                                                style: TextStyle(
                                                    fontWeight:
                                                        FontWeight.bold)),
//                      InkWell(
//                        onTap: () {
////                          Navigator.push(this.context,
////                              CupertinoPageRoute(builder: (BuildContext context) {
////                                return LeaveMsgPage(widget.orderID);
////                              }));
//                        },
//                        child: Container(
//                          width: 70,
//                          height: 30,
//                          margin: EdgeInsets.symmetric(vertical: 5),
//                          decoration: BoxDecoration(
//                              color: ColorsUtil.hexToColor('#3E62CE'),
////            border: Border.all(color: Colors.blue.withAlpha(60), width: 1.0),
//                              borderRadius: BorderRadius.all(Radius.circular(5))),
//                          child: Center(
//                            child: Text(
//                              '工单留言',
//                              style: TextStyle(fontSize: 14, color: Colors.white),
//                            ),
//                          ),
//                        ),
//                      )
                                          ],
                                        ),
                                        Divider(),
                                        GestureDetector(
                                          onTap: () {
                                            push(
                                                context,
                                                OrderRecordPage(
                                                    widget.orderId));
                                          },
                                          child: Column(
                                            children: List.generate(
                                                tempList.length,
                                                (position) => Container(
                                                      color: Colors.white,
                                                      padding: EdgeInsets.only(
                                                          left: 10, right: 10),
                                                      child: IntrinsicHeight(
                                                        child: Row(
                                                          children: [
                                                            //这个Container描绘左侧的线和圆点
                                                            Container(
                                                              margin: EdgeInsets
                                                                  .only(
                                                                      left: 10),
                                                              width: 20,
                                                              //需要根据文本内容调整高度，不然文本太长会撑开Container，导致线会断开
//                        height: getHeight(recordList[position].stateName),
                                                              child: Column(
                                                                //中心对齐，
                                                                mainAxisAlignment:
                                                                    MainAxisAlignment
                                                                        .center,
                                                                children: [
                                                                  Expanded(
                                                                      flex: 1,
                                                                      child:
                                                                          Container(
                                                                        //第一个item圆点上方的线就不显示了
                                                                        width: position ==
                                                                                0
                                                                            ? 0
                                                                            : 1,
                                                                        color: Colors
                                                                            .grey
                                                                            .shade300,
                                                                      )),
                                                                  //第一个item显示稍大一点的绿色圆点
                                                                  position == 0
                                                                      ? Stack(
                                                                          //圆心对齐（也就是中心对齐）
                                                                          alignment:
                                                                              Alignment.center,
                                                                          children: <
                                                                              Widget>[
                                                                            //为了实现类似阴影的圆点
                                                                            Container(
                                                                              height: 16,
                                                                              width: 16,
                                                                              decoration: BoxDecoration(
                                                                                color: Colors.red.shade200,
                                                                                borderRadius: BorderRadius.all(Radius.circular(10)),
                                                                              ),
                                                                            ),
                                                                            Container(
                                                                              height: 10,
                                                                              width: 10,
                                                                              decoration: BoxDecoration(
                                                                                color: Colors.red,
                                                                                borderRadius: BorderRadius.all(Radius.circular(7)),
                                                                              ),
                                                                            ),
                                                                          ],
                                                                        )
                                                                      : Container(
                                                                          height:
                                                                              10,
                                                                          width:
                                                                              10,
                                                                          decoration:
                                                                              BoxDecoration(
                                                                            color:
                                                                                Colors.grey.shade300,
                                                                            borderRadius:
                                                                                BorderRadius.all(Radius.circular(5)),
                                                                          ),
                                                                        ),
                                                                  Expanded(
                                                                      flex: 1,
                                                                      child:
                                                                          Container(
                                                                        width: position ==
                                                                                tempList.length - 1
                                                                            ? 0
                                                                            : 1,
                                                                        color: Colors
                                                                            .grey
                                                                            .shade300,
                                                                      )),
                                                                ],
                                                              ),
                                                            ),
                                                            Expanded(
                                                              child: Padding(
                                                                padding:
                                                                    EdgeInsets
                                                                        .fromLTRB(
                                                                            20,
                                                                            5,
                                                                            20,
                                                                            5),
                                                                child: Text(
                                                                  '${tempList[position].createDate.replaceAll('T', ' ')}    ${tempList[position].content}',
                                                                  style:
                                                                      TextStyle(
                                                                    //第一个item字体颜色为绿色+稍微加粗
                                                                    color: position ==
                                                                            0
                                                                        ? Colors
                                                                            .red
                                                                        : Colors
                                                                            .black,
                                                                    fontWeight: position ==
                                                                            0
                                                                        ? FontWeight
                                                                            .w600
                                                                        : null,
                                                                  ),
                                                                  overflow:
                                                                      TextOverflow
                                                                          .ellipsis,
                                                                  maxLines: 1,
                                                                ),
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    )).toList(),
                                          ),
                                        ),
//            Divider(),
                                        InkWell(
                                            child: Padding(
                                              padding: EdgeInsets.all(10),
                                              child: Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.center,
                                                children: [
                                                  Text(
                                                    '查看更多',
                                                    style:
                                                        TextStyle(fontSize: 12),
                                                  ),
                                                  Image.asset(
                                                    'assets/right.png',
                                                    width: 15,
                                                    height: 15,
                                                  )
                                                ],
                                              ),
                                            ),
                                            onTap: () {
                                              push(
                                                  context,
                                                  OrderRecordPage(
                                                      widget.orderId));
                                            })
                                      ],
                                    ))
                              ]),
                            ),
                          ],
                        )),
                  ),
                  Container(
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(25, 5, 20, 5),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          ElevatedButton(
                              onPressed: () {
                                showActions();
                              },
                              child: Text('快捷操作')),
                        ],
                      )),
                ],
              ),
            ),
      floatingActionButton: FloatingActionButton(
        heroTag: null,
        onPressed: () async {
          push(context, CreateOrderPage(2));
          // ignore: deprecated_member_use
//          Scaffold.of(context).showSnackBar(
//            SnackBar(content: Text('Favorited')),
//          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  void showActions() {
    var actions = ['取消工单', '催单', '留言', '修改服务类型', '修改产品'];
    showModalBottomSheet(
        isScrollControlled: false,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
        context: context,
        builder: (context) => SafeArea(
          child: Container(
                height: (56 * actions.length).toDouble(),
                child: Column(
                  children: List.generate(
                      5,
                      (index) => Column(
                        children: [
                          InkWell(
                                child: Container(
                                    height: 55,
                                    child: Center(
                                        child: Text(
                                      actions[index],
                                      textAlign: TextAlign.center,
                                    ))),
                            onTap: () async {
                                  Navigator.pop(context);
                                  switch(index){
                                    case 0:
                                      var result=await push(context, UrgePage(widget.orderId,1));
                                      print('取消工单$result');
                                      if(result!=null){
                                        getOrderDetail();
                                      }
                                      break;
                                    case 1:
                                      var result=await push(context, UrgePage(widget.orderId,0));
                                      print('催单$result');
                                      if(result!=null){
                                        getOrderDetail();
                                      }
                                      break;
                                    case 2:
                                      var result=await push(context, LeaveMsgPage(widget.orderId));
                                      print('留言$result');
                                      if(result!=null){
                                        getOrderDetail();
                                      }
                                      break;
                                    case 3:
                                      var result=await push(context, ChangeServiceTypePage(order.typeID,order.guarantee,widget.orderId));
                                      print('修改服务类型$result');
                                      if(result!=null){
                                        getOrderDetail();
                                      }
                                      break;
                                    case 4:
                                      var result=await push(context,ChangeProdPage(order));
                                      print('修改服务产品$result');
                                      if(result!=null){
                                        getOrderDetail();
                                      }
                                      break;
                                    default:
                                      break;
                                  }
                            },
                              ),
                          Visibility(child: Divider(height: 1,),visible: index!=4,)
                        ],
                      )).toList(),
                ),
              ),
        ));
  }
}
